/***
 * Excerpted from "Stripes: and Java Web Development is Fun Again",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/fdstr for more book information.
***/
package stripesbook.action.user.folders;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.annotation.security.RolesAllowed;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.HttpCache;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import org.stripesbook.rayures.view.ViewObject;
import org.stripesbook.rayures.view.ViewTag;
import org.stripesbook.rayures.view.stripes.SForm;
import org.stripesbook.rayures.view.stripes.SFormat;
import org.stripesbook.rayures.view.stripes.SHidden;
import org.stripesbook.rayures.view.stripes.SLink;
import org.stripesbook.rayures.view.stripes.SParam;
import stripesbook.model.Attachment;
import stripesbook.model.Message;
import stripesbook.view.MessageAction;

@HttpCache(allow=false)
@RolesAllowed({
  "Administrator",
  "User if ${user eq message.folder.user}"
})
public class MessageDetailsActionBean extends FoldersActionBean {
    private Message message;
    public Message getMessage() {
        return message;
    }
    public void setMessage(Message message) {
        this.message = message;
    }
    @DefaultHandler
    public void view() {
    }
    public Attachment attachment;

    public Resolution downloadAttachment()
        throws FileNotFoundException
    {
        String fileName = attachment.getFileName();
        String filePath = attachmentDao.getFilePath(attachment);
        return new StreamingResolution(attachment.getContentType(),
            new FileInputStream(filePath)).setFilename(fileName);
    }

    public SForm getForm() {
      return tag(SForm.class).beanclass(MessageListActionBean.class)
        .add(tag(MessageAction.class).folders(getUser().getFolders()))
        .add(tag(ViewTag.class).tagName("div")
          .add(tag(SHidden.class).name("selectedMessages").value(getMessage().getId())));
    }

    public ViewObject<?> getAttachmentLinkFor(Attachment attachment) {
      return tag(ViewObject.class)
        .add(tag(SLink.class)
          .add(tag(SParam.class).name("attachment")
            .add(tag(SFormat.class).value(attachment)))
          .add(attachment.getFileName()))
        .add("(" + attachment.getSize() + " bytes)")
        .add("<br/>");
    }
    
    public SLink getBackToListLink() {
      return tag(SLink.class).beanclass(MessageListActionBean.class)
        .label(bundle.get("messageDetails.backToList"));
    }
}
